﻿using IRepository;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace Repository
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly MyContext context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context"></param>
        public BaseRepository(MyContext context)
        {
            this.context = context;
        }
        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity">添加实体</param>
        /// <returns>返回添加实体成功或失败</returns>
        public async Task<bool> AddAsync(T entity)
        {
            await context.Set<T>().AddAsync(entity);
            return await context.SaveChangesAsync() > 0 ? true : false;
        }
        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="entity">删除实体</param>
        /// <returns>返回删除实体成功或失败</returns>
        public async Task<bool> DeleteAsync(T entity)
        {
            context.Set<T>().Remove(entity);
            return await context.SaveChangesAsync() > 0 ? true : false;
        }
        /// <summary>
        /// 根据Id查找数据的方法
        /// </summary>
        /// <param name="id">查</param>
        /// <returns>返回查找数据的方法</returns>
        public async Task<T> GetAll(int id)
        {
            return await context.Set<T>().FindAsync(id);
        }
        /// <summary>
        /// 根据Id查找数据的实体
        /// </summary>
        /// <param name="id">查</param>
        /// <returns>返回查找数据的实体</returns>
        public async Task<T> GetAll(Expression<Func<T, bool>> predicate)
        {
            return await context.Set<T>().Where(predicate).FirstOrDefaultAsync();
        }
        /// <summary>
        /// 查询所有数据的方法
        /// </summary>
        /// <returns>返回查找数据的方法</returns>
        public IQueryable<T> GetAllAsync()
        {
            return context.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 查询所有数据的实体
        /// </summary>
        /// <returns>返回查询所有数据的实体</returns>
        public IQueryable<T> GetAllAsync(Expression<Func<T, bool>> predicate)
        {
            return context.Set<T>().Where(predicate).AsQueryable();
        }

        public Task<int> UpdateAss(List<T> entities)
        {
            context.Set<T>().UpdateRange(entities);
            return context.SaveChangesAsync();
        }

        /// /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="entity">修改实体</param>
        /// <returns>返回修改实体成功或失败</returns>
        public async Task<bool> UpdateAsync(T entity)
        {
            context.Set<T>().Update(entity);
            return await context.SaveChangesAsync() > 0 ? true : false;
        }

        public async Task<int> UpdateAsyncs(T entity)
        {
            context.Set<T>().Update(entity);
            return await context.SaveChangesAsync();
        }
    }
}
